package com.sky.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.properties.BaiduMapProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrdersService;
import com.sky.service.ShoppingCartService;
import com.sky.utils.SearchHttpAK;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private BaiduMapProperties baiduMapProperties;

    public static final String URL  = "https://api.map.baidu.com/geocoding/v3?";

    /**
     * 用户下单--最终目的，将订单数据存入表中
     *
     * @param dto
     * @return
     */
    @Override
    public OrderSubmitVO addOrder(OrdersSubmitDTO dto) throws Exception {

        //查询地址表查询收货人
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        if (addressBook == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //查询用户表，获取用户相关信息
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.queryById(userId);
        if (user == null) {
            throw new OrderBusinessException(MessageConstant.USER_NOT_LOGIN);
        }

        //查询购物车数据
        List<ShoppingCart> cartList = shoppingCartMapper.list(userId);
        if (cartList == null || cartList.isEmpty()) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //增加距离判断逻辑
        SearchHttpAK snCal = new SearchHttpAK();

        String origin= coordinate(baiduMapProperties.getAddress());//获取店铺经纬度
        String address = addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
        String destination= coordinate(address);//获取店铺经纬度


        Map params2 = new LinkedHashMap<String, String>();
        params2.put("origin", origin);
        params2.put("destination", destination);
        params2.put("ak", baiduMapProperties.getAk());

        //调用百度地图api,获得返回数据
        StringBuffer stringBuffer = snCal.requestGetAK(baiduMapProperties.getURL(), params2);
        //解析json数据
        JSONObject jsonObject = JSONObject.parseObject(stringBuffer.toString());
        if (jsonObject.getInteger("status") == 0) {
            //获取距离
            JSONArray routes = jsonObject.getJSONObject("result").getJSONArray("routes");
            Integer distance = (Integer) routes.getJSONObject(0).get("distance");
            log.info("配送距离：{}米", distance);
            if (distance > 5000) {//超出5公里，不能配送
                throw new OrderBusinessException(MessageConstant.DISTANCE_OUT_OF_RANGE);
            }
        }else {
            String msg = jsonObject.get("message").toString();
            throw new OrderBusinessException(msg);
        }



        // 1.构造订单数据
        Orders orders = new Orders();
        // 2.插入订单数据到orders表中
        BeanUtils.copyProperties(dto, orders);
        orders.setNumber(System.currentTimeMillis() + "");
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(addressBook.getPhone());//查询地址表查询收货人手机号
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());//收货人//查询地址表查询收货人
        orders.setUserName(user.getName());//根据当前登录用户id查询当前下单的人名
        ordersMapper.insert(orders);
        // 3.构造订单明细列表数据--从购物车获取订单明细数据
        List<OrderDetail> orderDetails = new ArrayList<>();//查询购物车放入集合
        //循环遍历购物车明细数据，存入oreder_detail中
        cartList.forEach(cart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail, "id");
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        });
        //批量插入订单明细数据        // 4.将订单明细列表数据批量插入到order_detail表中
        orderDetailMapper.insertBatch(orderDetails);
        // 5.清空购物车数据（自己名下的）
        shoppingCartMapper.delete(ShoppingCart.builder().id(userId).build());
        // 6.构造vo对象并返回
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }

    
    /**
     * 获取经纬度
     * @param address
     * @return
     * @throws Exception
     */
    private String coordinate(String address) throws Exception {
        SearchHttpAK snCal = new SearchHttpAK();
        //调用百度API获取经纬度
        Map params1 = new LinkedHashMap<String, String>();
        params1.put("address", address );
        params1.put("output", "json");
        params1.put("ak", baiduMapProperties.getAk());

        StringBuffer str1 = snCal.getCoordinate(URL , params1);
        JSONObject jsonObject1 = JSONObject.parseObject(str1.toString());
        String coordinate = "";
        if(jsonObject1.getInteger("status") == 0){
            BigDecimal lng = (BigDecimal) jsonObject1.getJSONObject("result").getJSONObject("location").get("lng");//获取经度
            BigDecimal lat = (BigDecimal) jsonObject1.getJSONObject("result").getJSONObject("location").get("lat");//获取纬度
            lng = lng.setScale(6, BigDecimal.ROUND_HALF_UP);
            lat = lat.setScale(6, BigDecimal.ROUND_HALF_UP);
            log.info("经纬度：" + lng + "," + lat);
            coordinate = lat + "," + lng;
            log.info(coordinate);
        }
        return coordinate;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
/*        Long userId = BaseContext.getCurrentId();
        User user = userMapper.queryById(userId);*/
/*
        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;*/
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
    }

    /**
     * 分页查询订单
     * @param dto
     * @return
     */
    @Override
    public PageResult queryHistoryOrders(OrdersPageQueryDTO dto) {
        dto.setUserId(BaseContext.getCurrentId());
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<OrderVO> page = ordersMapper.queryHistoryOrders(dto);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO orderDetail(Long id) {
        // 根据订单id查询当前订单
        OrderVO orderVO = ordersMapper.getById(id);

        // 查询订单明细列表
        List<OrderDetail> orderDetailList = orderDetailMapper.list(id);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        //获取订单中的商品
        //Order order =   ordersMapper.getById(id);
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);

        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCartMapper.insert(shoppingCart);
        }
    }

    /**
     * 条件搜索订单
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<OrderVO> page = ordersMapper.conditionSearch(dto);
        page.forEach(orderVO -> {
            List<OrderDetail> details = orderDetailMapper.getByOrderId(orderVO.getId());
            String detailInfo = "";
            for (OrderDetail detail : details) {
                detailInfo += detail.getName() + " ";
            }
            orderVO.setOrderDishes(detailInfo);
        });
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 订单统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {

        Integer confirmed = ordersMapper.searchNumber(Orders.CONFIRMED);//已接单（待派送）confirmed
        Integer deliveryInProgress = ordersMapper.searchNumber(Orders.DELIVERY_IN_PROGRESS);//派送中deliveryInProgress
        Integer toBeConfirmed = ordersMapper.searchNumber(Orders.TO_BE_CONFIRMED);//待接单toBeConfirmed
        OrderStatisticsVO vo = OrderStatisticsVO.builder()
                .toBeConfirmed(toBeConfirmed)
                .confirmed(confirmed)
                .deliveryInProgress(deliveryInProgress)
                .build();
        return vo;
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancelById(Long id) {
        Orders orders = Orders.builder().id(id).status(Orders.CANCELLED).cancelReason("用户取消").build();
        ordersMapper.update(orders);
    }

    @Override
    public void cancelByIds(OrdersCancelDTO ordersCancelDTO) {
         ordersMapper.update(Orders.builder().id(ordersCancelDTO.getId()).cancelReason(ordersCancelDTO.getCancelReason()).cancelTime(LocalDateTime.now()).status(Orders.CANCELLED).build());
    }

    @Override
    public void delivery(Long id) {
        ordersMapper.update(Orders.builder().id(id).status(Orders.DELIVERY_IN_PROGRESS).build());
    }

    @Override
    public void repetitions(Long id) {
        ordersMapper.update(Orders.builder().id(id).status(Orders.COMPLETED).build());

    }

    @Override
    public void confirm(Long id) {
        ordersMapper.update(Orders.builder().id(id).status(Orders.COMPLETED).estimatedDeliveryTime(LocalDateTime.now().plusMinutes(30)).build());

    }

    /**
     * 开始接单业务
     *
     * @param ordersConfirmDTO
     * @return
     */
    @Override
    public OrderStatisticsVO orderReceiving(OrdersConfirmDTO ordersConfirmDTO) {
        // 更新当前订单状态为3已接单状态
        ordersConfirmDTO.setStatus(Orders.CONFIRMED);
        ordersMapper.updateStatus(ordersConfirmDTO);

        // 统计当前待接单数量 和 待派送数量
        Integer countToBe = ordersMapper.getCountByStatus(Orders.TO_BE_CONFIRMED);
        Integer countConfirm = ordersMapper.getCountByStatus(Orders.CONFIRMED);

        return OrderStatisticsVO.builder()
                .toBeConfirmed(countToBe)
                .confirmed(countConfirm)
                .build();
    }

    /**
     * 开始拒单业务
     *
     * @param ordersRejectionDTO
     * @return
     */
    @Override
    public OrderStatisticsVO orderRejecting(OrdersRejectionDTO ordersRejectionDTO) {

        // 更新当前订单状态为6已取消状态 和 更新日志信息
        ordersMapper.update(Orders.builder()
                .id(ordersRejectionDTO.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersRejectionDTO.getRejectionReason())
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .build());


        // 统计当前待接单数量
        Integer countToBe = ordersMapper.getCountByStatus(Orders.TO_BE_CONFIRMED);
        return OrderStatisticsVO.builder()
                .toBeConfirmed(countToBe)
                .build();
    }


}
